from django.shortcuts import render, redirect
from django.http import JsonResponse
from django.views import View
# Create your views here.

from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator

from django.contrib.auth import get_user_model
from django.db.models import F

# 从系统中获取自己定义的user表
User = get_user_model()

from operation import models
from article.models import ArticleModel


class ArticleClick(View):
    """
    文章点赞功能
    """

    # def get(self, request, *args, **kwargs):
    #     id = request.GET.get('id', None)
    #     if id:
    #         models.ArticleModel.objects.filter(id=id).update(fav_num=F('fav_num') + 1)
    #     return redirect('index')

    def post(self, request, *args, **kwargs):
        # 先判断用户是否已经登录,否则就返回错误
        id = request.POST.get('id', None)
        if request.user.is_authenticated and id:
            user = User.objects.filter(username=request.user).first()
            if models.UserClickArticle.objects.filter(user=user, blog_id=id):
                ArticleModel.objects.filter(id=id).update(click_num=F('click_num') - 1)
                models.UserClickArticle.objects.filter(blog_id=id).delete()
                return JsonResponse({'code': 2, 'message': '取消点赞'})
            else:
                # 判断该用户是否已经点赞,如已经点赞就不能点赞
                ArticleModel.objects.filter(id=id).update(click_num=F('click_num') + 1)
                # 插入数据
                models.UserClickArticle.objects.create(user=user, blog_id=id)
                # 更新博客点赞数
                return JsonResponse({'code': 0, 'message': '点赞成功'})
        else:
            return JsonResponse({'code': 1, 'message': '请登录'})
